package com.fanyi.baidu;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;

import com.alibaba.fastjson.JSON;
import com.util.HttpClientUtil;

/**
 * @author liuchao
 * @version $Id: BiduTransTest.java,v 0.1 2012-9-10 ����5:21:46 liuchao Exp $
 */
public class BaiduTransTest {
    
    private  final static String url = "http://openapi.baidu.com/public/2.0/bmt/translate";
    
    
    
    public void getJsonByGet()throws HttpException, IOException {
        Map<String, String> parame = new HashMap<String,String>();
        parame.put("client_id", "3QWsqZ0C5XEKVBgRQ56Kigjb");
        parame.put("q", URLEncoder.encode("测试","UTF-8"));
        parame.put("from", "en");
        parame.put("to", "en");
        int i = 0;
        NameValuePair[] nameValue = new NameValuePair[parame.size()];
        StringBuffer data = new StringBuffer().append(url).append("?");
                for (String key : parame.keySet()) {
                    nameValue[i++] = new NameValuePair(key, parame.get(key));
                    data.append(key + "=" + parame.get(key) + "&");
                }
        Map<String, String> backMap = HttpClientUtil.getHttpClientXML(data.toString());
        String backXML = backMap.get("backXml");
        System.out.println("backXML:"+backXML);
        BaiduTransResult baiduTransResult = JSON.parseObject(backXML.trim(),BaiduTransResult.class);
//        System.out.println("errorCode:"+baiduTransResult.getError_code());
    }
    
    public void getJsonByPost()throws HttpException, IOException {
        Map<String, String> parame = new HashMap<String,String>();
        parame.put("client_id", "3QWsqZ0C5XEKVBgRQ56Kigjb");
        parame.put("q", "测试");
        parame.put("from", "zh");
        parame.put("to", "en");
        String json = new String( HttpClientUtil.postSimpleMethodHttpClent(url, parame),"utf-8");
        
        System.out.println("json:"+json);
        BaiduTransResult baiduTransResult = JSON.parseObject(json.trim(),BaiduTransResult.class);
        List<TransResult> transResult = baiduTransResult.getTrans_result();
        for(TransResult result : transResult) {
            System.out.println("src:"+URLDecoder.decode( result.getSrc(),"utf-8"));
            System.out.println("dst:"+URLDecoder.decode( result.getDst(),"utf-8"));
        }
    }
    
    public static void main(String args[]) throws HttpException, IOException
    {
        BaiduTransTest test = new BaiduTransTest();
        
        for(int i=0;i<2010;i++)
        {
            System.out.println("i:"+i);
            test.getJsonByGet();
        }
    }
    
}
